package pri.hillchen.std.netty.timeserver.unpack;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 16:55 2018/3/30 0030.
 */
public class DecodeTimeClientHandler extends ChannelHandlerAdapter {
    private int counter;

    private ByteBuf createMsg(){
        byte[] req = (UnpackTimeServerHandler.QUERY_TIME_COMMAND + UnpackTimeServerHandler.LINE_SEPARATOR).getBytes();
        ByteBuf firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
        return  firstMessage;
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for(int i = 0;i<100;i++){
            ctx.writeAndFlush(createMsg());
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        String body = (String) msg;
        System.out.println(String.format("Now is:%s,has handler order:%s",body,++counter));

        /*//获取到当前时间后要立即退出，否则客户端不会关闭。
        if(ctx != null){
            ctx.close();
        }*/
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
